package src

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case

packageName = "" // 根据选中的目录自动获取

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    def baseName = javaName(table.getName(), true, true)
    packageName = getPackageName(dir)
    // 创建mapper接口
    new File(dir, baseName + "Mapper.xml").withPrintWriter("utf-8") { out -> generateFile(out, baseName) }
}

// 创建mapper接口
def generateFile(out, baseName) {
    out.println "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\" >"
    out.println "<mapper namespace=\"com.alpaca.module.${packageName}.mapper.${baseName}Mapper\">"
    out.println "</mapper>"
}


/**
 *
 * @param str
 * @param capitalize 是否需要开头大写
 * @param needRemovePrefix 是否需要去掉前缀
 * @return
 */
def javaName(str, capitalize, needRemovePrefix) {
    if (needRemovePrefix) {
        def index = str.indexOf("_")
        if (index != null) {
            str = str.substring(str.indexOf("_") + 1)
        }
    }
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

/**
 * 通过选中的文件夹路径获取包名
 * @param dir
 * @return
 */
def getPackageName(dir) {
    def path = dir.toString()
    def index = path.lastIndexOf("\\");
    if (index != -1) {
        path = path.substring(index + 1)
    } else {
        path = ""
    }
    return path
}
